<template>
  <div class="header-container">
    <div class="l-content">
    
    </div>
    <div class="r-content">
      <span class="welcome-title">欢迎您，{{ nickname }}</span>
      <el-dropdown class="dropdown-menu">
        <span class="el-dropdown-link">
          <img :src="userImage">
        </span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item @click.native="dialogVisible = true">修改密码</el-dropdown-item>
          <el-dropdown-item @click.native="logout">退出</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    
    <!--    修改密码对话框   -->
    <el-dialog title="重置用户密码"
               width="30%"
               :visible.sync="dialogVisible"
               :close-on-click-modal="false"
               :modal-append-to-body='false'
               @close="handleCloseDialog">
      <el-form :model="dataForm"
               label-width="100px"
               :rules="dataFormRules"
               ref="dataForm"
               label-position="right"
               size="small"
               status-icon
      >
        <el-form-item label="旧密码:" prop="oldPassword">
          <el-input v-model="dataForm.oldPassword" type="password" auto-complete="off" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码:" prop="newPassword" label-width="100px">
          <el-input v-model="dataForm.newPassword" type="password" auto-complete="off" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码:" prop="newPassword2" label-width="100px">
          <el-input v-model="dataForm.newPassword2" type="password" auto-complete="off" show-password></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="margin-top: 5px;">
        <el-button type="primary" @click.native="handleUpdataPassword">修改</el-button>
        <el-button @click.native="dialogVisible = false" type="danger">取消</el-button>
      </div>
    </el-dialog>
  
  </div>
</template>

<script>


import {checkOldPassword, updatePassword} from "@/api/user";

export default {
  name: "CommonHeader",
  data() {
    //旧密码验证器
    const oldPwdValidator = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入旧密码'));
      }
      //调用接口验证旧密码
      this.toCheckOldPassword(value,
          function () {
            callback();
          }, function () {
            callback('旧密码验证失败');
          })
    };
    
    const newPwdValidator = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请再次输入密码'));
      }
      if (this.dataForm.newPassword !== value) {
        callback(new Error("密码不一致"));
      } else {
        callback()
      }
    };
    
    return {
      nickname: localStorage.getItem("nickname"),
      userImage: require("@/assets/images/user.png"),
      dialogVisible: false,
      dataForm: {
        oldPassword: '',
        newPassword: '',
        newPassword2: ''
      },
      dataFormRules: {
        oldPassword: [{
          required: true,
          validator: oldPwdValidator,
          trigger: 'blur',
        }],
        newPassword: [{
          required: true,
          message: '请输入新密码',
          trigger: 'blur'
        }],
        newPassword2: [{
          required: true,
          validator: newPwdValidator,
          trigger: 'change'
        }]
      },
      
    }
  },
  methods: {
    logout() {
      this.$store.commit("removeToken")
      this.$store.commit("removeUserInfo")
      this.$router.push("/login")
    },
    //关闭时候清空表单
    handleCloseDialog() {
      this.$refs.dataForm.resetFields();
    },
    // 校验旧密码
    toCheckOldPassword(oldPwd, success, error) {
      const username = localStorage.getItem("username");
      if (!oldPwd) return;
      const params = {
        username: username,
        password: oldPwd
      }
      checkOldPassword(params).then(res => {
        const {data} = res;
        if (data.code === 200) {
          success()
        } else {
          error()
        }
      }).catch(() => {
        error()
      })
    },
    //修改密码，调用接口更改
    handleUpdataPassword() {
      const username = localStorage.getItem("username");
      const params = {
        username: username,
        password: this.dataForm.newPassword2
      }
      this.$refs.dataForm.validate((valid) => {
        if (!valid) return;
        updatePassword(params).then(res => {
              const {data} = res;
              if (data.code == '200') {
                this.$message.success(data.msg)
                this.dialogVisible = false;
                this.$refs.dataForm.resetFields();
              }
            }
        ).catch(err => {
          console.log("err", err)
          this.$message.error(err.data.message)
        })
      })
    }
  },
  computed: {}
}
</script>

<style lang="less" scoped>

.header-container {
  display: flex;
  justify-content: space-between;
  width: 100%;
  
  .l-content {
    display: flex;
    align-items: center;
    
  }
  
  .r-content {
    display: flex;
    align-items: center;
    
    .welcome-title {
      margin-right: 10px;
    }
    
    .dropdown-menu {
      
      .el-dropdown-link {
        display: flex;
        align-items: center;
        
        img {
          height: 36px;
          width: 36px;
          border-radius: 18px;
        }
      }
    }
  }
}

.el-dialog{
  padding: 5px 20px;
}
</style>